<template>
	<view class="main">
		<u-sticky>
			<view id="header" class="header">
				<view>
					<!-- #ifdef MP-ALIPAY -->
					<navBar :title="title" titleColor="#000" :needMarginBottom="false"></navBar>
					<!--#endif-->
					<!-- #ifdef MP-WEIXIN-->
					<navBar :title="title" titleColor="#000" :needMarginBottom="false"></navBar>
					<!--#endif-->
				</view>
			</view>
		</u-sticky>
		<scroll-view scroll-y="true" @scrolltolower="reachBottom" :style="{ height: height + 'px'}"
			:scroll-with-animation="true" :enable-back-to-top="true">
			<view>
				<view>
					<noticeBar :merchantStoreId="Number(deviceVo.merchantStoreId)" bgColor="#ff7242"
						messageColor="#FFFFFF" :needMarginBottom="false" />
				</view>
				<view>
					<!--    iot头部显示开始   -->
					<view class="member-info" :class="deviceVo.isBluetooth ? 'u-row-around':''">
						<image :src="`${staticFileUrl}/image/pay/vending-machine/phone_max.png`"
							v-if="!deviceVo.isBluetooth" style="width: 400rpx;" mode="widthFix" />

						<view class="member-info-left">
							<view class="info-item" :style="!deviceVo.isBluetooth ? 'width: 400rpx':''">
								<image class="info-icon"
									:src="`${staticFileUrl}/image/pay/vending-machine/number_icon.svg`">
								</image>
								编号：{{parameter.deviceNo}}
							</view>
							<view class="info-item" style="margin-top: 20rpx;"
								:style="!deviceVo.isBluetooth ? 'width: 400rpx':''">
								<image class="info-icon"
									:src="`${staticFileUrl}/image/pay/vending-machine/phone_icon.svg`">
								</image>
								电话：<text>
									<text v-if="customerServiceInfoVo.serviceMobilePhone"
										@click="call(customerServiceInfoVo.serviceMobilePhone)">{{customerServiceInfoVo.serviceMobilePhone}}</text>
									<text v-else-if="customerServiceInfoVo.serviceFixedTelephone"
										@click="call(customerServiceInfoVo.serviceFixedTelephone)">{{customerServiceInfoVo.serviceFixedTelephone}}</text>
								</text>
							</view>
						</view>
						<view class="u-flex u-row-between u-font-22" v-if="deviceVo.isBluetooth">
							<view class="u-m-20 state-box">
								<view class="white-circle">
									<view class="frame">
										<view :class="'power-'+calculateBatteryPercentage(connectionPower)"></view>
									</view>
								</view>
								<text>电量{{calculateBatteryPercentage(connectionPower)}}</text>
							</view>
							<view class="u-m-20 state-box">
								<image class="state-img"
									:src="`${staticFileUrl}/image/pay/vending-machine/bluetooth.png`"></image>
								<text>{{connectionStatus == 1 ? '连接中' : connectionStatus == 2 ? '已连接' : '连接失败'}}</text>
							</view>
							<view class="u-m-20 state-box">
								<image class="state-img" @click="intoMember"
									:src="`${staticFileUrl}/image/pay/vending-machine/personalCenter.png`"></image>
								<text>个人中心</text>
							</view>
						</view>
						<view class="member-info-right" v-else>
							<image class="info-icon" @click="intoMember"
								:src="`${staticFileUrl}/image/pay/vending-machine/member_icon.svg`"></image>
						</view>
					</view>
					<!--    iot头部显示结束      -->

					<!--   轮播图共用开始  -->
					<view class="demo-block" v-if="merchantBannerList.length > 0">
						<u-swiper previousMargin="10" nextMargin="10" bgColor="rgb(255,255,255)"
							:list="merchantBannerList" @click="jumpBeforeTheAppletFromSwiper()" height="190"
							imgMode="widthFix" radius="10" keyName="url" indicatorStyle="bottom: 50rpx"
							@change="e => current = e.current" :autoplay="true">
							<view slot="indicator" class="indicator">
								<view class="indicator__dot" v-for="(item, index) in merchantBannerList" :key="index"
									:class="[index === current && 'indicator__dot--active']"></view>
							</view>
						</u-swiper>
					</view>
					<!--   轮播图共用结束  -->
				</view>
				<view class="memu" v-if="deviceVo.commodityGroupSwitch">
					<u-tabs @click="memuClick" lineColor="rgb(254, 97, 66)"
						:inactiveStyle="{ color: '#000000',fontSize:'28rpx'}" :list="listMenu"
						:activeStyle="{color: '#000000',fontSize:'28rpx',fontWeight:'500'}" lineHeight="5"
						lineWidth="24">
					</u-tabs>
				</view>
			</view>
			<view class="content-box u-m-t-13">
				<u-grid :border="false" :col="col" v-if="!$u.test.isEmpty(merchantBanner) && listData.length == 0">
					<u-grid-item @click="jumpBeforeTheAppletFromFirst(merchantBanner)">
						<view class="goods-card">
							<u--image :showLoading="true" :src="merchantBanner.url" :width="imgWidth"
								:height="imgHeightAdv" radius="5">
							</u--image>
						</view>
					</u-grid-item>
				</u-grid>

				<!-- #ifdef MP-ALIPAY || MP-WEIXIN -->
				<u-grid :border="false" :col="col">
					<u-grid-item @click="jumpBeforeTheAppletFromFirst(merchantBanner)"
						v-if="!$u.test.isEmpty(merchantBanner) && listData.length > 0">
						<view class="goods-card">
							<u--image :showLoading="true" :src="merchantBanner.url" radius="5" :width="imgWidth"
								:height="imgHeightAdv">
							</u--image>
						</view>
					</u-grid-item>
					<u-grid-item v-for="(listItem,listIndex) in listData" :key="listIndex"
						@click="purchase(listItem,listIndex)">
						<view class="goods-card" @click="addShoppingCard($event,listIndex)">
							<view class="img-view">
								<u--image v-if="listItem.fileName" :showLoading="true"
									:src="imageUrl + listItem.fileName" :width="imgWidth" :height="imgHeight"
									radius="5">
								</u--image>
								<u--image v-else :showLoading="true"
									:src="staticFileUrl+'/image/common/default_goods_image.svg'" :width="imgWidth"
									:height="imgHeight">
								</u--image>
								<!-- 印章效果 -->
								<view class="seal" :class="col == 2?'seal-ding-lan':'seal-ding'"
									v-if="listItem.stock<=0">
									<view class="seal-son">
										<span class="seal-span">已售完</span>
									</view>
								</view>
							</view>
							<view class="goods-info">
								<view class="goods-info-name u-lint-ellipsis-1">
									{{listItem.cname}}
								</view>
								<view class="goods-info-stock">
									<view v-if="deviceVo.productDisplayType!==2">
										货道:{{listItem.alias}}
									</view>
									<view>
										库存:{{listItem.stock}}
									</view>
								</view>
								<view class="goods-info-price">
									<view>
										<text>￥</text>{{listItem.retailPrice}}
									</view>
								</view>
							</view>
						</view>
					</u-grid-item>
				</u-grid>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<view class="grid-h5">
					<view v-for="(listItem,listIndex) in listData" :key="listIndex"
						@click="purchase(listItem,listIndex)">
						<view class="goods-card" @click="addShoppingCard($event,listIndex)">
							<view class="img-view">
								<u--image v-if="listItem.fileName" :showLoading="true"
									:src="imageUrl + listItem.fileName" width="200rpx" height="200rpx">
								</u--image>
								<u--image v-else :showLoading="true"
									:src="staticFileUrl+'/image/common/default_goods_image.svg'" width="200rpx"
									height="200rpx">
								</u--image>
								<!-- 印章效果 -->
								<view class="seal" style="position: absolute;
                 <!-- #ifdef MP-ALIPAY ||  MP-WEIXIN -->
								top:30rpx;
                <!--#endif-->
                  " v-if="listItem.stock<=0">
									<view class="seal-son">
										<span class="seal-span">已售完</span>
									</view>
								</view>
							</view>
							<view class="goods-info">
								<view class="goods-info-name">
									{{listItem.cname}}
								</view>
								<view class="goods-info-stock">
									<view v-if="deviceVo.productDisplayType!==2">
										货道:{{listItem.alias}}
									</view>
									<view>
										库存:{{listItem.stock}}
									</view>
								</view>
								<view class="goods-info-price">
									<view>
										<text>￥</text>{{listItem.retailPrice}}
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- #endif -->
				<u-toast ref="uToast" />
			</view>
			<u-loadmore :status="loadStatus" height="70rpx" :line="true"></u-loadmore>
		</scroll-view>
		<!-- 小球动画 -->
		<view :animation="animationY" :style="'position:fixed;top:' + ballY + 'px;'" v-if="showBall">
			<view class="ball" :animation="animationX" :style="'position:fixed;left:' + ballX + 'px;'">
				<u--image class="cart_img" :showLoading="true" :src='imageUrl+listData[listIndex].fileName'
					mode="aspectFit" v-if="listData[listIndex].fileName" width="200rpx" height="170rpx"
					:errorIcon='staticFileUrl+"/image/common/default_goods_image.svg"'></u--image>
				<u--image :showLoading="true" :src='staticFileUrl+"/image/common/default_goods_image.svg"'
					mode="aspectFit" v-else width="200rpx" height="170rpx"></u--image>
			</view>
		</view>
		<view class="footer-box" id="footer">

			<u-transition :show="show">
				<view class="goods-list">
					<view class="goods-list-title">
						售货机-新体验
					</view>
					<view class="goods-list-tips">
						<view class="goods-list-tips-left">
							选购商品:（{{cardList.length?cardList.length:0}})
						</view>
						<view class="goods-list-tips-right" @click="clearCard">
							<text>清空</text><u-icon name="trash" color="rgb(156,156,154)" size="18"></u-icon>
						</view>
					</view>

					<u-list :height="cardHeight+'rpx'" v-if="cardList && cardList.length>0">
						<view style="padding:0 0 10rpx 0;">
							<u-list-item v-for="(item,index) in cardList" :key="index">
								<view class="goods-list-item" id="itemHeight">
									<text class="item-name">{{item.cname}}</text>
									<text class="item-parice">￥{{item.retailPrice}}</text>
									<view class="plus-minus-btn" style="width: 30%;text-align: right">
										<img @click="goodsMinus(index,2)"
											:src="`${staticFileUrl}/image/pay/vending-machine/minus.svg`"
											v-if="item.num>0" />
										<text v-if="item.num>0">{{item.num}}</text>
										<img @click="goodsPlus(index,2)"
											:src="`${staticFileUrl}/image/pay/vending-machine/plus.svg`" />
									</view>
								</view>
							</u-list-item>
						</view>
					</u-list>
				</view>
			</u-transition>
			<view :class="deviceVo.shoppingCart?'shopping-card':'shopping-card-hide'">
				<view class="shopping-card-left" @click="closeCard">
					<img class="card-icon" id="cart"
						:src="`${staticFileUrl}/image/pay/vending-machine/shopping_card_icon.svg`" />
					<view class="num-cion" v-if="totalNum>0">
						<text>{{totalNum}}</text>
					</view>
				</view>
				<view class="shopping-card-left shopping-card-right">
					<text>￥</text><text class="totalPrice">{{totalPrice}}</text>
					<view class="settlement" @click="settlement">去结算</view>
				</view>
			</view>
			<view>

				<u-tabbar :value="value4" @change="name => value4 = name" :fixed="false" :placeholder="false"
					activeColor="rgb(254, 97, 66)" :safeAreaInsetBottom="false">
					<u-tabbar-item text="首页" icon="home"></u-tabbar-item>
					<u-tabbar-item text="订单" icon="order" @click="intoOrder"></u-tabbar-item>
				</u-tabbar>
			</view>
		</view>
		<u-overlay :show="show" @click="show = false" zIndex='2'></u-overlay>
		<u-popup :show="successfulShipmentShow" mode="center" :round="20" :safeAreaInsetBottom="false"
			@touchmove.stop.prevent="">
			<view class="expireDeviceBox" style="max-width: 600rpx">
				<view style="padding: 30rpx 20rpx;">
					<view class="expireDeviceBoxTitle">
						出货成功
					</view>
					<view style="margin-top: 10rpx;">
						如未弹开货道，可前往"订单"
						找到出货失败订单"查看详情"在最下方点击
						"重新出货"按钮尝试重新出货
					</view>
					<view class="noteTips">注意重新出货限支付后20分钟内可用</view>
				</view>
				<view class="expireDeviceBoxBottomBox">
					<view @click="goToOrder" class="expireDeviceBoxButtomBox-2">
						前往
					</view>
					<view @click="successfulShipmentShow=false" class="expireDeviceBoxButtomBox">
						知道了
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Decimal from "decimal.js";
	import service from "@/components/service/service";
	import noticeBar from "@/components/notice-bar/notice-bar";
	import {
		eventBus
	} from '@/main.js'
	export default {
		name: "vendingMachine",
		components: {
			service,
			noticeBar
		},
		data() {
			return {
				staticFileUrl: this.$configPath.staticFileUrl,
				imageUrl: this.$configPath.imageUrl,
				merchantBannerList: [],
				merchantBanner: {},
				typeArray: [],
				current: 0,
				height: 0,
				cardHeight: 20,
				title: '',
				titleTemplate: '售货机',
				deviceVo: {
					merchantStoreId: '',
					rateEach: 1,
					measuringUnit: '币',
				},

				listMenu: [],
				listMenuId: [], //分组id集合
				cardList: [], //购物车临时变量，用于请求后端参数
				cardListRef: [], //购物车临时变量，用于回显购物车数据
				listData: [], //商品列表
				parameter: {
					pageNum: 1,
					totalPage: 1,
					pageSize: 20,
					deviceNo: '',
					commodityGroupId: '', //分组id
					salesmanId: '',
				},
				customerServiceInfoVo: {
					id: '',
					serviceName: '',
					serviceWeChatNumber: '',
					serviceWeChatQr: '',
					serviceMobilePhone: '',
					serviceFixedTelephone: '',
					memberId: ''
				},
				loadStatus: 'nomore', //列表底部加载更多状态
				value4: 0, //底部跳转下标
				totalPrice: new Decimal(0), //购物车总金额
				totalNum: 0, //购物车总数量
				phone: 13800138000,
				show: false, //购物车显示关闭
				flag: true, //防止重复点击
				rightListSum: [{
					showDel: false,
					delAnimation: false, // 删除动画
					sum: 0,
				}],
				showBall: false, // 小球是否显示
				animationY: '', // 动画Y
				animationX: '', // 动画X
				ballY: '', // 小球当前位置Y
				ballX: '', // 小球当前位置X
				listIndex: 0,
				connectionStatus: 1,
				connectionPower: 0,
				innerAudioContext: null,
				//未播放0 播放过1
				playbackStatus: 0,
				//蓝牙出货成功弹框
				successfulShipmentShow: false,
				//默认是三列
				col: 3,
				imgWidth: '200rpx',
				imgHeight: '200rpx',
				imgHeightAdv: '337rpx',
			}
		},
		// onReady() {
		// 	this.getPomHeight()
		// },
		created() {
			// 监听事件
			eventBus.$on('connectionStatus', this.handleEventConnectionStatus)
			eventBus.$on('connectionPower', this.handleEventConnectionPower)
		},
		methods: {
			goToOrder() {
				this.$Router.push({
					name: 'my-order',
				});
			},
			handleEventConnectionStatus(connectionStatus) {
				console.log('connectionStatus变化', connectionStatus)
				this.connectionStatus = connectionStatus;
				if (this.connectionStatus == 2) {
					// 获取发送电池配置
					this.setBatteryNumber();
				}
			},
			handleEventConnectionPower(connectionPower) {
				console.log('connectionPower变化', connectionPower)
				this.connectionPower = connectionPower;
			},
			setBatteryNumber() {
				let param = {
					deviceNo: this.parameter.deviceNo,
				}
				this.$api('device.setBatteryNumber', param).then(res => {
					if (res.status == 0) {
						if (!this.$u.test.isEmpty(res.data)) {
							this.$bluetooth.sendMy(res.data, 0);
							// this.customerServiceInfoVo = res.data
						}
					}
				}).catch(err => {
					uni.hideLoading();
				})
			},

			creatAudio() {
				var that = this;
				//目前发起苹果会加载两次导致音频播放两次,所以加个判断每次只播放一次
				if (this.playbackStatus == 0) {
					this.innerAudioContext = uni.createInnerAudioContext(); //创建实例
					this.innerAudioContext.autoplay = true; //设置是否自动播放
					this.innerAudioContext.src = this.staticFileUrl + '/image/mp3/bluetooth-welcome.mp3'
					this.innerAudioContext.play()
					this.innerAudioContext.onPlay(() => {
						that.playbackStatus = 1;
						console.log('开始播放')
					});
					this.innerAudioContext.onEnded(() => {
						console.log('语音播报结束')
						this.innerAudioContext.destroy() // 销毁
					});
					this.innerAudioContext.onError(() => {
						console.log('语音播报失败')
						this.innerAudioContext.destroy() // 销毁
					});
				}
			},
			calculateBatteryPercentage(batteryBars) {
				const percentagePerBar = 20;
				return Math.floor(batteryBars * percentagePerBar);
			},
			init(deviceNo, deviceVo) {
				this.parameter.deviceNo = deviceNo;
				this.parameter.salesmanId = deviceVo.salesmanId
				// console.log('deviceVo',deviceVo)
				console.log('业务员ID：', this.parameter.salesmanId)
				this.deviceVo = deviceVo;
				this.title = this.deviceVo.storeName;
				if (this.deviceVo.isBluetooth) {
					//连接设备
					this.$bluetooth.initBluetooth(deviceNo, this.deviceVo.isBluetooth);
					//启动蓝牙连接状态的监听
					this.$bluetooth.startBLEConnectionStateListening(deviceNo);
					this.creatAudio();
				}
				this.findGroupNameByDeviceNo();
				this.findDeviceGoodsByDeviceNo();
				this.findServiceByMerchantStoreId();
				this.findMerchantStoreById();
				// this.findMerchantBannerList();
				setTimeout(() => {
					this.getPomHeight()
				}, 500);
			},

			jumpBeforeTheAppletFromSwiper(e) {
				console.log('e', e)
				console.log('this.merchantBannerList[e]', this.merchantBannerList[e])
				this.goWapBindingDevice(this.merchantBannerList[e].navWeChatAppId)
			},

			jumpBeforeTheAppletFromFirst(merchantBanner) {
				console.log('merchantBanner', merchantBanner)
				this.goWapBindingDevice(merchantBanner.navWeChatAppId)
			},

			goWapBindingDevice(navWeChatAppId) {
				console.log('navWeChatAppId', navWeChatAppId)
				if (this.$u.test.isEmpty(this.parameter.deviceNo)) {
					this.$helpers.toast("设备号为空");
					return
				}
				if (this.$u.test.isEmpty(navWeChatAppId)) {
					return
				}
				let nav;
				console.log('salesmanId', this.parameter.salesmanId)
				if (!this.$u.test.isEmpty(this.parameter.salesmanId)) {
					nav = 'pages/index?deviceNo=' + this.parameter.deviceNo + '&fromAgentId=' + this.parameter.salesmanId
				} else {
					nav = 'pages/index?deviceNo=' + this.parameter.deviceNo
				}
				uni.navigateToMiniProgram({
					appId: navWeChatAppId,
					path: nav,
					envVersion: this.$configPath.envVersion,
					success: res => {
						// 打开成功
						console.log("打开成功路径：", nav);
					},
					fail: err => {
						console.log(err);
					}
				});
			},
			findMerchantStoreById() {
				this.$api("merchantStore.findMerchantStoreById", {
					id: getApp().globalData.currMerchantStore.id
				}).then(res => {
					if (res.status == 0) {
						if (!this.$u.test.isEmpty(res.data)) {
							this.noticeMessage = res.data;
						}
					}
				}).catch(err => {

				})
			},
			// 添加购物车
			addShoppingCard(e, listIndex) {
				if (!this.deviceVo.shoppingCart) {
					return;
				}
				if (this.totalNum >= this.deviceVo.shoppingCartCapacity) {
					return;
				}
				if (this.listData[listIndex].num >= this.listData[listIndex].stock) {
					return;
				}
				// x, y表示手指点击横纵坐标, 即小球的起始坐标

				// #ifdef  MP-WEIXIN
				let ballX = e.detail.x - 60,
					ballY = e.detail.y;
				this.createAnimation(ballX, ballY);
				// #endif
				// #ifdef  MP-ALIPAY
				let ballX = e.detail.clientX - 60,
					ballY = e.detail.clientY;
				this.createAnimation(ballX, ballY);
				// #endif
			},
			// 延迟执行
			setDelayTime(sec) {
				return new Promise((resolve, reject) => {
					setTimeout(() => {
						resolve()
					}, sec)
				});
			},
			// 创建动画
			async createAnimation(ballX, ballY) {
				try {
					const e = await this.getSystemInfo();
					var bottomX = 0; // 结束位置X
					var bottomY = e.windowHeight - 50; // 结束位置Y
					var animationX = this.flyX(bottomX, ballX); // 创建小球水平动画
					var animationY = this.flyY(bottomY, ballY); // 创建小球垂直动画
					this.ballX = ballX; // 小球当前位置X
					this.ballY = ballY; // 小球当前位置Y
					this.showBall = true; // 显示小球
					await this.setDelayTime(100);
					this.animationX = animationX.export(); // 执行动画X
					this.animationY = animationY.export(); // 执行动画Y
					await this.setDelayTime(200);
					this.animationX = this.flyX(0, 0, 0).export(); // 执行动画X
					this.animationY = this.flyY(0, 0, 0).export(); // 执行动画Y
					this.showBall = false; // 隐藏小球
					await this.setDelayTime(200);
				} catch (error) {
					console.error(error);
				}
			},
			// 获取系统信息
			getSystemInfo() {
				return new Promise((resolve, reject) => {
					uni.getSystemInfo({
						success: function(res) {
							resolve(res);
						},
						fail: function(error) {
							reject(error);
						}
					});
				});
			},
			// 水平动画
			flyX(bottomX, ballX, duration) {
				/**
				 * bottomX 结束位置
				 * ballX 开始位置
				 * duration 动画持续时间
				 */
				let animation = uni.createAnimation({
					duration: duration || 200,
					timingFunction: 'linear',
				})
				animation.translateX(bottomX - ballX).step(); // 动画效果
				return animation;
			},
			// 垂直动画
			flyY(bottomY, ballY, duration) {
				/**
				 * bottomY 结束位置
				 * ballY 开始位置
				 * duration 动画持续时间
				 */
				let animation = uni.createAnimation({
					duration: duration || 200,
					timingFunction: 'ease-in',
				})
				animation.translateY(bottomY - ballY).step(); // 动画效果
				return animation;
			},
			//查询广告: 6某台售货机顶部轮播图，7某台售货机第一个商品位为广告图
			findMerchantBannerList() {
				let params = {
					merchantStoreId: getApp().globalData.currMerchantStore.id,
					deviceNo: this.parameter.deviceNo,
					typeArray: [6, 7],
				}
				// console.log(params,"params")
				this.$api("merchantBanner.findMerchantBannerList", params).then(res => {
					if (res.status == 0) {
						console.log(res.data)
						this.merchantBannerList = res.data;
						if (this.merchantBannerList.length > 0) {
							this.merchantBannerList.forEach(item => {
								item.url = this.imageUrl + item.fileName;
								//获取商品位的广告
								if (item.type == 7) {
									this.merchantBanner = item;
								}
							})
						}
						//过滤掉广告位
						this.merchantBannerList = this.merchantBannerList.filter(item => item.type != 7);
						// this.merchantBannerList = [];
						console.log('轮播图广告：', this.merchantBannerList)
					}
				}).catch(err => {

				})
			},
			findServiceByMerchantStoreId() {
				let param = {
					merchantStoreId: getApp().globalData.currMerchantStore.id,
					deviceNo: this.parameter.deviceNo,
				}
				this.$api('customerServiceInfo.findCustomerServiceInfoByApplet', param).then(res => {
					if (res.status == 0) {
						if (!this.$u.test.isEmpty(res.data)) {
							this.customerServiceInfoVo = res.data
						}
					}
				}).catch(err => {
					uni.hideLoading();
				})
			},
			findDeviceGoodsByDeviceNo() {
				if (this.$u.test.isEmpty(this.parameter.deviceNo)) {
					this.$helpers.toast("设备号为空");
					return
				}
				uni.showLoading({
					title: '加载中...'
				});
				this.$api('device.findDeviceGoodsByDeviceNo', this.parameter).then(res => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
					if (res.status == 0) {
						this.parameter.pageNum = res.data.pageNum;
						this.parameter.totalPage = res.data.pages;
						this.loadStatus = res.data.list.length === 20 ? 'loadmore' : 'nomore';
						this.listData = [...this.listData, ...res.data.list];
						this.getCacheCardData();
						this.listData.forEach(item => {
							item.num = 0;
						});
						if (this.deviceVo.productDisplayType === 2) {
							this.listData.sort((a, b) => b.stock - a.stock);
						}

						// 更新 listData 中的 num，匹配 cardList 中的数据
						if (this.cardList && this.cardList.length > 0) {
							for (let i = 0; i < this.listData.length; i++) {
								const listItem = this.listData[i];
								const cardListItem = this.cardList.find(cardItem => cardItem.displayRackItemId ===
									listItem.displayRackItemId);

								if (cardListItem) {
									listItem.num = cardListItem.num;
								}
							}
						}
						if (this.parameter.pageNum >= res.data.pages) {
							this.loadStatus = 'nomore';
						}

					} else {
						this.$helpers.toast(res.msg);
					}
				}).catch(err => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			findGroupNameByDeviceNo() {
				if (this.$u.test.isEmpty(this.parameter.deviceNo)) {
					this.$helpers.toast("设备号为空");
					return
				}
				this.$api('device.findGroupNameByDeviceNo', this.parameter).then(res => {
					uni.stopPullDownRefresh();
					if (res.status == 0) {
						this.listMenu = [{
							name: '全部'
						}];
						this.listMenuId = res.data;
						if (this.deviceVo.commodityGroupSwitch) {
							this.listMenuId.forEach(item => {
								if (item.cgName) {
									this.listMenu.push({
										'name': item.cgName
									});
								}
							});
							this.$forceUpdate();
						}

					} else {
						this.$helpers.toast(res.msg);
					}
				}).catch(err => {
					uni.stopPullDownRefresh();
				})
			},
			memuClick(item) {
				this.parameter.pageNum = 1;
				this.parameter.totalPage = 1;
				this.parameter.pageSize = 20;
				this.listData = [];
				if (item.index > 0) {
					this.parameter.commodityGroupId = this.listMenuId[item.index - 1].cgId;
				} else {
					this.parameter.commodityGroupId = '';
				}
				this.findDeviceGoodsByDeviceNo();
				this.total();
			},

			serviceShow() {
				this.$nextTick(() => {
					this.$refs.service.serviceShow();
				});
			},
			intoOrder(url) {
				uni.navigateTo({
					url: 'pages-member/my-order/my-order'
				});
				this.clearCard();
				this.value4 = 0;
			},
			intoMember(url) {
				uni.switchTab({
					url: 'pages/member/member-center/member-center'
				});
				this.clearCard();
				this.value4 = 0;
			},
			intoMember2() {
				uni.switchTab({
					url: 'pages/member/member-center/member-center-weChatApplet-5'
				});
				this.clearCard();
				this.value4 = 0;
			},
			call(phone) {
				if (!phone) {
					this.$helpers.toast('商家暂未预留联系电话');
					return;
				}
				uni.makePhoneCall({
					phoneNumber: phone,
					success(res) {
						console.log("拨打电话成功", res)
					},
					fail(err) {
						console.log("拨打电话失败", err)
					}

				});

			},
			purchase(listItem, listIndex) {
				if (!uni.$u.test.isEmpty(this.deviceVo.shoppingCart) && this.deviceVo.shoppingCart) {
					this.goodsPlus(listIndex, 1)
				} else {
					this.notShoppingCartModel(listItem)
				}
			},
			goodsPlus(listIndex, type) {
				this.listIndex = listIndex;
				if (type === 1) {
					if (this.totalNum >= this.deviceVo.shoppingCartCapacity) {
						this.$helpers.toast("购物车已满");
						return;
					}
					if (this.listData[listIndex].num >= this.listData[listIndex].stock) {
						this.$helpers.toast("当前商品无法再添加了");
						this.listData[listIndex].num = this.listData[listIndex].stock;
						return;
					}
					this.listData[listIndex].num++;
				} else {
					if (this.totalNum >= this.deviceVo.shoppingCartCapacity) {
						this.$helpers.toast("购物车已满");
						return;
					}
					if (this.cardList[listIndex].num >= this.cardList[listIndex].stock) {
						this.$helpers.toast("当前商品无法再添加了");
						this.cardList[listIndex].num = this.cardList[listIndex].stock;
						return;
					}
					this.cardList[listIndex].num++;
				}
				this.total(type);
			},
			goodsMinus(listIndex, type) {

				if (this.cardList[listIndex].num <= 0) {
					this.cardList[listIndex].num = 0;
					return;
				}
				this.cardList[listIndex].num--;
				this.total(type);

			},

			total(type) {
				let totalNum = 0;
				let totalPrice = Decimal(0);

				// 更新 cardList
				this.listData.forEach((item, j) => {
					let foundIndex = this.cardList.findIndex(item2 => item2.displayRackItemId === item
						.displayRackItemId);
					if (foundIndex !== -1) {

						if (type === 1) {
							this.cardList[foundIndex] = this.listData[j];
						} else {
							this.listData[j] = this.cardList[foundIndex];
						}
					} else if (item.num > 0) {

						this.cardList.push(item);

					}
				});

				// 移除数量为 0 的商品
				this.cardList = this.cardList.filter(item => item.num > 0);

				// 计算总数和总价
				this.cardList.forEach(item => {
					totalNum += item.num;
					totalPrice = Decimal(totalPrice).add(Decimal(item.retailPrice).mul(Decimal(item.num)));
					item.displayRackItemAlias = item.alias;
				});

				this.totalNum = totalNum;
				this.totalPrice = totalPrice;
				this.cacheCardData();

				// 更新 cardHeight
				if (this.cardList.length === 0) {
					this.cardHeight = 10;
				} else {
					this.cardHeight = Math.min(100 * this.cardList.length + 40, 400);
				}
				this.$forceUpdate();
			},

			cacheCardData() {
				this.cardListRef = JSON.parse(JSON.stringify(this.cardList));
				this.getCacheCardData();
			},
			getCacheCardData() {
				this.cardList = JSON.parse(JSON.stringify(this.cardListRef));
			},
			reachBottom() {
				if (this.loadStatus == 'nomore') {
					return;
				}
				this.loadStatus = 'loading';
				this.parameter.pageNum++;
				this.findDeviceGoodsByDeviceNo();
			},
			getPomHeight() {
				let that = this
				//#ifdef MP-WEIXIN || H5
				wx.nextTick(() => {
					let query = wx.createSelectorQuery().in(that)
					query.select('#header').boundingClientRect()
					query.select('#footer').boundingClientRect()
					query.exec(res => {
						that.height = wx.getSystemInfoSync().windowHeight;
						that.height -= res[0].height;
						that.height -= res[1].height;
						console.log(that.height)

					});
				});
				//#endif

				//#ifdef MP-ALIPAY
				my.createSelectorQuery().selectAll('#header, #footer').boundingClientRect().exec((rects) => {
					const headerHeight = rects[0][0].height;
					const footerBoxHeight = rects[0][1].height;
					const windowHeight = my.getSystemInfoSync().windowHeight;
					const height = windowHeight - headerHeight - footerBoxHeight;
					this.height = height - 80;
				});
				//#endif
			},
			closeCard() {
				this.show = !this.show;
			},
			clearCard() {
				this.show = false;
				this.listData.forEach(item => {
					item.num = 0;
				});
				this.cardList = [];
				this.cardListRef = [];
				this.total();
			},
			notShoppingCartModel(item) {
				if (item == null) {
					this.$helpers.toast('该商品不存在，请刷新页面查看');
					return
				}
				this.cardList = [];
				item.num = 1;
				this.cardList.push(item);
				this.settlement();
			},
			settlement() {
				if (this.deviceVo.isBluetooth) {
					// #ifdef  MP-ALIPAY
					this.$helpers.toast('支付宝暂不支持，请使用微信扫码');
					return;
					// #endif
					if (this.connectionStatus == 2) {
						// 蓝牙可用时才执行后续逻辑
						this.vendingMachinePay();
					} else if (this.connectionStatus == 1) {
						this.$helpers.toast('正在连接蓝牙设备中...');
					} else if (this.connectionStatus == 3) {
						this.$bluetooth.disconnectPrompt();
					}
				} else {
					this.vendingMachinePay();
				}
			},
			vendingMachinePay() {
				console.log('进入vendingMachinePay')
				if (!this.flag) {
					return;
				}
				uni.showLoading({
					title: '支付中...'
				});
				this.flag = false;
				if (this.$u.test.isEmpty(this.parameter.deviceNo)) {
					uni.hideLoading();
					this.$helpers.toast('设备号不能为空');
					this.flag = true;
					return
				}
				if (this.cardList.length == 0) {
					uni.hideLoading();
					this.$helpers.toast('请选择需要购买的商品');
					this.flag = true;
					return
				}
				// #ifdef  H5
				let channelType2 = ''
				var ua = window.navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == "micromessenger") {
					channelType2 = 'WX'
				} else if (ua.match(/AlipayClient/i) == "alipayclient") {
					channelType2 = 'ALI'
				}
				// #endif
				let param = {
					deviceNo: this.parameter.deviceNo,
					deviceDtoList: this.cardList,
					// #ifdef  MP-WEIXIN
					channelType: 'WX',
					paymentEnvironment: 2
					// #endif
					// #ifdef  MP-ALIPAY
					channelType: 'ALI',
					paymentEnvironment: 3
					// #endif
					// #ifdef  H5
					channelType: channelType2,
					// #endif
				}
				console.log(param, "参数")
				getApp().globalData.isPaymentInProgress = true;
				this.$api("order.vendingMachinePay", param).then(res => {
					if (res.status == 0) {
						uni.hideLoading();
						this.flag = true;
						// #ifdef  H5
						this.$payment.paymentPage(res.data, this.parameter.deviceNo, '/api/deviceNo/', () => {
							setTimeout(() => {
								this.clearCard();
								this.listData = [];
								this.parameter.pageNum = 1;
								this.parameter.totalPage = 1;
								this.findDeviceGoodsByDeviceNo();
							}, 1000)
						});
						return;
						// #endif
						this.$payment.juHePay(res.data, () => {
							setTimeout(() => {
								this.clearCard();
								this.listData = [];
								this.parameter.pageNum = 1;
								this.parameter.totalPage = 1;
								this.findDeviceGoodsByDeviceNo();
								if (this.deviceVo.isBluetooth) {
									this.successfulShipmentShow = true;
								}
							}, 1000)
						}, (failData) => {
							setTimeout(() => {
								getApp().globalData.isPaymentInProgress = false;
							}, 1000)
						});
					} else {
						this.flag = true;
						uni.hideLoading();
						this.$helpers.toast(res.msg);
					}
				}).catch(err => {
					this.flag = true;
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	/deep/ .u-notice-bar {
		background-color: #fe7242 !important;
	}

	/deep/ .indicator__dot {
		border: 2rpx solid #fff !important;
	}

	.expireDeviceBox {
		font-size: 28rpx;
		color: rgba(13, 13, 13, 0.9);
		background: linear-gradient(155deg, #afb9f9 0%, white 45%);
		border-radius: 40rpx;

		.expireDeviceBoxTitle {
			text-align: center;
			margin-top: 10rpx;
			margin-bottom: 30rpx;
			font-size: 34rpx;
			font-weight: 700;
		}

		.noteTips {
			font-weight: 700;
			color: red;
			text-align: center;
			margin-top: 40rpx;
			font-size: 24rpx;
		}

		.expireDeviceBoxBottomBox {
			display: flex;
			justify-content: space-between;
			font-size: $f-base;

			.expireDeviceBoxButtomBox-2 {
				text-align: center;
				padding: 10rpx 0 40rpx 0;
				flex: 1;
				color: $u-primary;
			}

			.expireDeviceBoxButtomBox {
				text-align: center;
				padding: 10rpx 0 40rpx 0;
				flex: 1;
			}
		}
	}

	.state-box {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;

		.white-circle {
			width: 46rpx;
			height: 46rpx;
			background-color: #FFFFFF;
			border-radius: 50%;
			margin-bottom: 5rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.frame {
				border-color: #6b6464;
				border-style: solid;
				border-width: 1px;
				height: 10rpx;
				width: 30rpx;

				.power-20 {
					height: 100%;
					width: 20%;
					background-color: #ea0808;
				}

				.power-40 {
					height: 100%;
					width: 40%;
					background-color: #FF9800;
				}

				.power-60 {
					height: 100%;
					width: 60%;
					background-color: #FF9800;
				}

				.power-80 {
					height: 100%;
					width: 80%;
					background-color: #4cd964;
				}

				.power-100 {
					height: 100%;
					width: 100%;
					background-color: #4cd964;
				}
			}
		}

		.state-img {
			margin-bottom: 5rpx;
			width: 48rpx;
			height: 48rpx;
		}
	}

	.main {
		width: 100%;
		background-repeat: no-repeat;
		background-size: 100%;
		min-height: 100vh;
		//#ifdef H5
		min-height: 0vh;
		// #endif
		background-color: $uni-bg-color-hover;

		.header {
			padding-top: 170rpx;
			background: white;
		}

		//#ifdef H5
		.header {
			padding-top: 0rpx;
		}

		// #endif
		.member-info {
			height: 120rpx;
			padding: 20rpx;
			font-size: $f-base;
			color: white;
			display: flex;
			align-items: center;
			background: linear-gradient(90.00deg, rgb(255, 161, 65) -1.533%, rgb(254, 97, 66) 101.733%);


			.member-info-left {
				display: flex;
				flex-direction: column;

				.info-icon {
					width: 32rpx;
					height: 32rpx;
					margin-right: 15rpx;
				}

				.info-item {
					display: flex;
					align-items: center;
				}
			}

			.member-info-right {
				display: flex;
				flex-direction: column;
				align-items: center;
				width: 400rpx;

				.info-icon {
					width: 60rpx;
					height: 60rpx;
				}
			}
		}

		.memu {
			padding: 0rpx 50rpx 10rpx 50rpx;
			font-weight: 500;
			background: white;
		}

		.content-box {

			padding: 0 15rpx;
			background-color: $uni-bg-color-hover;

			.grid-h5 {
				height: 330rpx;
				//#ifdef H5
				height: 100% !important;
				// #endif
				border-radius: 10rpx;
				display: grid;
				grid-template-rows: repeat(3, 1fr);
				grid-template-columns: repeat(3, 1fr);
			}

			.goods-card-height {
				width: 200rpx;
				height: 330rpx;
			}

			.goods-card {
				//width: 200rpx;
				//height: 330rpx;
				background: rgb(255, 255, 255);
				margin: 6rpx 7rpx;
				padding: 15rpx;
				border-radius: 10rpx;

				.img-view {
					display: flex;
					justify-content: center;
					margin-bottom: 10rpx;

					.seal {
						width: 160rpx;
						height: 160rpx;
						border: solid 6rpx #B4B4B4;
						border-radius: 100%;
						background-color: rgba(255, 255, 255, 0.5);
						position: relative;
						display: flex;
						justify-content: center;
						align-items: center;
					}

					.seal-ding-lan {
						position: absolute;
						// #ifdef MP-ALIPAY ||  MP-WEIXIN
						top: 80rpx;
						// #endif
					}

					.seal-ding {
						position: absolute;
						// #ifdef MP-ALIPAY ||  MP-WEIXIN
						top: 30rpx;
						// #endif
					}

					.seal-son {
						width: 145rpx;
						height: 145rpx;
						border: solid 2rpx #B4B4B4;
						border-radius: 100%;
						background-color: rgba(255, 255, 255, 0.5);
						position: relative;

						.seal-span {
							position: absolute;
							top: 47rpx;
							text-align: center;
							font-size: 35rpx;
							transform: rotate(-35deg);
							right: 23rpx;
							color: #B4B4B4;
							font-weight: 900;
						}
					}

				}


				.goods-info {
					.goods-info-name {
						//white-space: nowrap;
						//overflow: hidden;
						//text-overflow: ellipsis;

						font-size: $f-base;
					}

					.goods-info-stock {
						display: flex;
						justify-content: space-between;
						font-size: 22rpx;
						color: rgba(34, 34, 34, 0.6);
						margin: 10rpx 0;
					}

					.goods-info-price {
						font-size: 30rpx;
						color: red;
						display: flex;
						align-items: center;
						justify-content: space-between;

						text {
							font-size: 24rpx;
						}

					}
				}
			}

		}

		.plus-minus-btn {
			display: flex;
			align-items: center;
			justify-content: flex-end;

			text {
				margin: 0 23rpx;
				color: rgba(34, 34, 34, 0.6);
			}

			img {
				width: 55rpx;
				height: 55rpx;
			}

			view {
				width: 90rpx;
				height: 45rpx;
				background: rgb(255, 170, 127);
				border-radius: 20rpx;
				color: rgba(34, 34, 34, 0.6);
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}


		.hide-block-alpay {
			height: 120rpx;
		}

		.hide-block-wx {
			height: 220rpx;
		}

		.hide-block-wx-v2 {
			height: 120rpx;
		}


		.footer-box {
			width: 100%;
			position: fixed;
			bottom: 0;
			z-index: 99;

			.goods-list {
				width: 100%;
				font-size: $f-base;
				background-color: white;

				/*设置底部定位 向上延伸*/
				.goods-list-title {
					color: rgb(104, 53, 8);
					background-color: rgb(254, 247, 218);
					text-align: center;
					padding: 20rpx 0;
					padding: 30rpx;
					font-size: 32rpx;
				}

				.goods-list-tips {
					padding: 25rpx 40rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					color: rgb(156, 156, 154);

					.goods-list-tips-right {
						display: flex;
						align-items: center;
						padding: 20rpx 0;

						text {
							margin-right: 10rpx;
						}
					}
				}

				.goods-list-item {
					padding: 15rpx 40rpx;
					color: rgb(104, 53, 8);
					display: flex;
					text-align: center;
					align-items: center;
					height: 75rpx;
					justify-content: space-between;

					.item-name {
						width: 40%;
						text-align: left;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					.item-price {
						width: 30%;
					}
				}
			}

			.transparent-item {
				height: 10rpx;
				background: rgba(0, 0, 0, 0);
			}

			.shopping-card-hide {
				display: none;
			}

			.shopping-card {
				padding-left: 40rpx;
				height: 100rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				background: rgba(0, 0, 0, 1);

				.shopping-card-left {
					height: 100%;
					display: flex;
					align-items: center;
				}

				.shopping-card-right {
					color: white;
					float: right;
					font-size: $f-xl;

					text {
						font-size: 22rpx;
					}

					.totalPrice {
						font-size: $f-xl;
						margin-right: 40rpx;
						margin-left: 10rpx;
					}

					.settlement {
						width: 250rpx;
						height: 100%;
						text-align: center;
						line-height: 100rpx;
						background: rgb(254, 212, 66);
						color: black;
						font-weight: 400;
					}

				}

				.card-icon {
					width: 70rpx;
					height: 70rpx;
				}

				.num-cion {
					width: 36rpx;
					height: 36rpx;
					background: rgb(255, 0, 0);
					position: relative;
					float: right;
					border-radius: 40rpx;
					color: white;
					margin-left: -20rpx;
					margin-top: -25rpx;
					text-align: center;
					line-height: 36rpx;
					font-size: 22rpx;
				}
			}
		}

		.flex {
			display: flex;
		}

		.true {
			border: 8rpx solid red;
		}

		.false {
			border: 2rpx solid #ccc;
		}

		.item {
			width: 50rpx;
			height: 50rpx;
			border-radius: 100%;
		}


		.but {
			margin: 10rpx;
			height: 60rpx;
			width: 80rpx;
			display: flex;
		}

		.ball {
			height: 40rpx;
			width: 40rpx;
			border-radius: 50%;
			position: fixed;
		}

		.ball image {
			width: 100%;
			height: 100%;
		}

		/* 从右到左 */
		.delRightShoppingCardAnimations {
			animation: delRightShoppingCardAnimation .5s;
		}

		@keyframes delRightShoppingCardAnimation {
			from {
				transform: translateX(100rpx) rotate(900deg);
				animation-timing-function: linear;
			}

			to {
				transform: translateX(0rpx) rotate(0);

			}
		}

		/* 从左到右 */
		.delLeftShoppingCardAnimations {
			animation: delLeftShoppingCardAnimation .5s;
		}

		@keyframes delLeftShoppingCardAnimation {
			from {
				transform: translateX(0rpx) rotate(0);
			}

			to {
				transform: translateX(100rpx) rotate(900deg);
				animation-timing-function: linear;
			}
		}

	}

	.blue-tooth {
		background: white;
		padding: 0rpx 30rpx;
	}

	.demo-block {
		background: #FFFFFF;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
	}

	.indicator {
		@include flex(row);
		justify-content: center;

		&__dot {
			height: 12rpx;
			width: 12rpx;
			border-radius: 200rpx;
			background-color: rgba(255, 255, 255, 0.35);
			margin: 0 10rpx;
			transition: background-color 0.3s;

			&--active {
				background-color: #ffffff;
			}
		}

		.indicator__dot--active {
			border: 2rpx solid #fff;
		}
	}

	.indicator-num {
		padding: 4rpx 0;
		background-color: rgba(0, 0, 0, 0.35);
		border-radius: 200rpx;
		width: 70rpx;
		@include flex;
		justify-content: center;

		&__text {
			color: #FFFFFF;
			font-size: 24rpx;
		}
	}
</style>